package com.yuqing.sentimentapp.home.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.text.TextUtils;
import android.view.ViewGroup;

import com.linkface.baselibrary.utils.CollectionUtils;
import com.yuqing.sentimentapp.channel.ChannelData;
import com.yuqing.sentimentapp.home.fragment.EarlyWarningFragment;
import com.yuqing.sentimentapp.home.fragment.NewsFragment;
import com.yuqing.sentimentapp.home.fragment.RecommendFragment;
import com.yuqing.sentimentapp.home.fragment.SpecialTopicFragment;

import java.util.HashMap;
import java.util.List;

public class HomeViewPagerAdapter extends FragmentPagerAdapter {

    private List<ChannelData> mTitles;
    private RecommendFragment recommendFragment;
    private SpecialTopicFragment specialTopicFragment;
    private EarlyWarningFragment earlyWarningFragment;
    private HashMap<String, Fragment> newsFragments = new HashMap<>();

    public HomeViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    public HomeViewPagerAdapter(FragmentManager fm, List<ChannelData> mTitles) {
        super(fm);
        this.mTitles = mTitles;
        initFragments();
    }

    private void initFragments() {
        recommendFragment = new RecommendFragment();
        specialTopicFragment = new SpecialTopicFragment();
        earlyWarningFragment = new EarlyWarningFragment();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return !CollectionUtils.isNullOrEmpty(mTitles) ? mTitles.get(position).getCategoryName() : "";
    }

    @Override
    public Fragment getItem(int position) {
        ChannelData channelData = mTitles.get(position);
        switch (channelData.getCategoryType()) {
            default:
                return new NewsFragment();
            case "R"://推荐
                return recommendFragment;
            case "N"://新闻
                if (newsFragments.containsKey(channelData.getOriginId())) {
                    return newsFragments.get(channelData.getOriginId());
                } else {
                    NewsFragment newsFragment = NewsFragment.newInstance(channelData.getOriginId());
                    newsFragments.put(channelData.getOriginId(), newsFragment);
                    return newsFragment;
                }
            case "T"://专题
                return specialTopicFragment;
            case "Y"://预警
                return earlyWarningFragment;
        }
    }

    @Override
    public int getCount() {
        return mTitles.size();
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }
}
